package com.tangly.module.controller;

import com.github.pagehelper.PageHelper;
import com.tangly.common.bean.ErrorResponse;
import com.tangly.common.bean.PageResponse;
import com.tangly.common.bean.SearchParam;
import com.tangly.common.exception.BusinessException;
import com.tangly.common.shiro.AuthInfo;
import com.tangly.module.entity.UserAuth;
import com.tangly.module.entity.UserInfo;
import com.tangly.module.service.IUserAuthService;
import com.tangly.module.service.IUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(description = "用户信息控制器", tags = "用户信息模块")
@Slf4j
@ApiResponses({@ApiResponse(code = 206, message = "业务逻辑无法执行", response = ErrorResponse.class)})
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private IUserAuthService iUserAuthService;

    @ApiOperation(value = "获取用户登录信息")
    @GetMapping("/getLoginInfo")
    @RequiresAuthentication
    public UserAuth getLoginInfo() throws BusinessException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            UserAuth userAuth = (UserAuth) subject.getPrincipal();
            return userAuth;
        } else {
            throw new BusinessException("用户信息不正确");
        }
    }

    @ApiOperation(value = "获取用户个人信息")
    @GetMapping("/getUserInfo")
    @RequiresAuthentication
    public UserInfo getUserInfo() throws BusinessException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            AuthInfo userAuth = (AuthInfo) subject.getPrincipal();
            UserInfo userInfo = iUserInfoService.selectByPrimaryKey(userAuth.getUserId());
            return userInfo;
        } else {
            throw new BusinessException("用户信息不正确");
        }
    }

    @ApiOperation(value = "获取用户列表")
    @PostMapping("/searchAuth")
    @RequiresAuthentication
    public PageResponse<UserAuth> getUserAuthList(@RequestBody SearchParam searchParam){
        PageHelper.startPage(searchParam.getPage(), searchParam.getSize());
        List<UserAuth> userAuths =  iUserAuthService.getUserAuthList();
        PageResponse<UserAuth> pageInfo = new PageResponse<>(userAuths);
        return pageInfo;
    }

}
